package com.powernode.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.vo.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 没有权限的handler
 */
@Component
public class AppAccessDeniedHandler implements AccessDeniedHandler {


    @Resource
    private ObjectMapper objectMapper;

    /**
     * 没有权限的时候security会执行该方法
     * @param request
     * @param response
     * @param accessDeniedException
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        Result result = new Result(-1, "没有权限");

        String jsonStr = objectMapper.writeValueAsString(result);
        response.getWriter().write(jsonStr);
    }
}
